from apps.common.base.dao import BaseDao
from apps.merchant.sku.serializers import *
from django.db.models import F
from apps.merchant.item.dao import ItemDao

class SkuDao(BaseDao):
    MODEL_CLASS = Sku
    SERI_CLASS = SkuBaseSerializer

    def create(self, data):
        res = super().create(data)
        # 同步商品的价格
        skus = self.findAll().filter(item__id=data.get('item')).order_by('sellingPrice')
        sku = skus.first()
        ItemDao().update(data.get('item'), {'sellingPrice': sku.sellingPrice, 'marketPrice': sku.marketPrice, 'discountPrice': sku.discountPrice})
        return res
    
    def update(self, obj_id, data):
        res = super().update(obj_id, data)
        # 同步商品的价格
        skus = self.findAll().filter(item__id=data.get('item')).order_by('sellingPrice')
        sku = skus.first()
        item = ItemDao().findOneByObjId(data.get('item'))
        params = {}
        if data.get('sellingPrice') and sku.sellingPrice != item.sellingPrice:
            params['sellingPrice'] = sku.sellingPrice
        if data.get('marketPrice') and sku.marketPrice != item.marketPrice:
            params['marketPrice'] = sku.marketPrice
        if  data.get('discountPrice') and sku.discountPrice != item.discountPrice:
            params['discountPrice'] = sku.discountPrice
        ItemDao().update(data.get('item'), params)
        return res

    # 增加库存
    def addStock(self, itemId, n):
        if not n:
            return
        try:
            item = SkuDao().findOneByObjId(itemId)
            item.stock = F('stock') + n
            item.save()
        except Exception as e:
            print(e)

    # 减少库存
    def subStock(self, itemId, n):
        if not n:
            return
        try:
            item = SkuDao().findOneByObjId(itemId)
            if item.stock > n:
                item.stock = F('stock') - n
            else:
                item.stock = 0
            item.save()
        except Exception as e:
            print(e)

    # 增加销量
    def addSales(self, itemId, n):
        if not n:
            return
        try:
            item = SkuDao().findOneByObjId(itemId)
            item.sales = F('sales') + n
            item.save()
        except Exception as e:
            print(e)

    # 减少销量
    def subSales(self, itemId, n):
        if not n:
            return
        try:
            item = SkuDao().findOneByObjId(itemId)
            item.sales = F('sales') - n
            item.save()
        except Exception as e:
            print(e)